from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
# Create your models here.

class Game(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50, null=False, blank=False, unique=True)
    tile = models.CharField(max_length=25, default='.......N...BE....WAS.....')
    players = models.ManyToManyField(User, through='GamePlayer')
    current_player = models.ForeignKey(User, related_name='playing')

    def get_players(self):
        return self.players.all().order_by('gameplayer__player_num')

    def get_player(self, player_num):
        return self.gameplayer_set.get(player_num=player_num).user
        
    @models.permalink
    def get_absolute_url(self):
        return ('game', [str(self.id)])
        self.player_num, 
    def get_winners(self):
        return self.players.filter(gameplayer__winner=True) \
                           .order_by('gameplayer__player_num')
    @classmethod
    def create_game(cls, players, name=None):
        if not name:
            name = "%s's game" % players[0].username
        game = cls(
            name=name,
            current_player=players[0],
        )
        game.save()
        for i, user in enumerate(players):
            player = GamePlayer(user=user, game=game, player_num=i)
            player.save()
        return game

    def __unicode__(self):
        game_str = u'Game %d - %s' % (self.pk, self.name)
        def mark_current_player(p):
            if p == self.current_player:
                return unicode(p) + '*'
            else:
                return unicode(p)
        players_str = u', '.join(map(mark_current_player, self.get_players()))
        return u'%s %s' % (game_str, players_str)

class Word(models.Model):
    word = models.CharField(max_length=50)
    score = models.IntegerField(default=0)

    def __unicode__(self):
        return u'%s' % (self.word)

class GamePlayer(models.Model):
    user = models.ForeignKey(User)
    game = models.ForeignKey(Game)
    player_num = models.IntegerField()
    score = models.IntegerField(default=0)
    winner = models.BooleanField(default=False)
    words = models.ManyToManyField(Word,blank=True)
    
    def get_words(self):
        return self.words.all()

    def __unicode__(self):
        return u'Player %d %s in game %d' % (self.player_num, self.user,
                                             self.game.pk)
        

    
class UsersInline(admin.TabularInline):
    model = Game.players.through

class GameAdmin(admin.ModelAdmin):
    list_display = [ 'name', 'tile','current_player' ]
    inlines = [ UsersInline, ]
    search_fields = [ 'name' ]

class WordAdmin(admin.ModelAdmin):
    list_display = [ 'word', 'score']
        
class GamePlayerAdmin(admin.ModelAdmin):
    list_display = [ 'user', 'game', 'player_num', 'score', 'winner' ]
    search_fields = [ 'user' ]
    inlines = [ UsersInline, ]
  
admin.site.register(Game, GameAdmin)
admin.site.register(Word, WordAdmin)
admin.site.register(GamePlayer, GamePlayerAdmin)
